package com.shulidata.mock.service.groovy;

import com.shulidata.mock.model.MockConf;
import com.shulidata.mock.service.MockConfService;
import groovy.lang.GroovyObject;
import org.aspectj.lang.reflect.InitializerSignature;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author fyduan
 * @date 16/4/29
 */
@Component
public class GroovyManager implements InitializingBean {

    private boolean inited = false;

    @Autowired
    MockConfService confService;

    // 保存Groovy实例
    private ConcurrentHashMap<String, GroovyScriptProcessor> groovyMaps = new ConcurrentHashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        initScript();
        inited = true;
    }

    // 系统启动则初始化脚本到JVM
    public void initScript() {
        List<MockConf> list = confService.loadAll();
        for (MockConf conf : list) {
            GroovyScriptProcessor processor = new GroovyScriptProcessor(conf.getScriptMethod(), conf.getScript());
            groovyMaps.put(conf.getId(), processor);
        }
    }

    // 刷新脚本
    public void refresh() {
        // 项目启动,如果还没有完成初始化,则直接返回
        if (!inited) return;
        List<MockConf> list = confService.findLastUpdateByInterval(60000L);
        for (MockConf conf : list) {
            if (conf.isDeleted()) {
                groovyMaps.remove(conf.getId());
                continue;
            }
            GroovyScriptProcessor processor = new GroovyScriptProcessor(conf.getScriptMethod(), conf.getScript());
            groovyMaps.put(conf.getId(), processor);
        }
    }

    public GroovyScriptProcessor getScriptProcessor(String scriptKey) {
        return groovyMaps.get(scriptKey);
    }

}
